package com.glepoch.springbootsecuritymybatis.controller.login;

import com.glepoch.springbootsecuritymybatis.bean.Menu;
import com.glepoch.springbootsecuritymybatis.bean.User;
import com.glepoch.springbootsecuritymybatis.service.menu.MenuService;
import com.glepoch.springbootsecuritymybatis.utils.QrCodeUtil;
import com.google.zxing.WriterException;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author ygl
 * @description 登录
 * @date 2021年08月20日 19:49
 */
@Controller
public class LoginController {
    @Autowired
    private QrCodeUtil qrCodeUtil;
    @Autowired
    private MenuService menuService;
    /*
     *
     * @author ygl
     * @description 跳转到登录页面
     * @date 2021/8/21/0021 15:17
     * @return java.lang.String
     */
    @RequestMapping(value = {"/"})
    public String toLogin(HttpServletRequest request) {
        request.setAttribute("name", "扫码登录");
        UUID uuid = UUID.randomUUID();
        String s = uuid.toString();
        request.setAttribute("loginuuid", s);//生成唯一id用于绑定用户
        return "login";
    }


    /*
     *
     * @author ygl
     * @description 生成二维码图片
     * @date 2021/8/21/0021 15:56
     * @param response
     * @param loginuuid 标识唯一的id，与扫码同步用
     */
    @RequestMapping("/login/qrImage")
    public void qr(HttpServletResponse response, String loginuuid) throws IOException, WriterException {
        byte[] b = qrCodeUtil.createQRCode(100, 100, "http://efqxta6a.ipyingshe.net/login/qrToLogin?loginuuid=" + loginuuid);
        ServletOutputStream os = response.getOutputStream();
        os.write(b);
        os.close();
    }

    /*
     *
     * @author ygl
     * @description 手机扫码后携带uuid再跳转回到登录页面（在手机端收集认证信息）
     * @date 2021/8/21/0021 16:01
     * @param loginuuid 标识唯一的id，与扫码同步用
     * @param model
     * @return java.lang.String
     */
    @RequestMapping("/login/qrToLogin")
    public String toLogin(String loginuuid, Model model) {
        model.addAttribute("loginuuid", loginuuid);
        return "qrLogin";
    }
    @RequestMapping("/login/qrLogin")
    @ResponseBody
    public String qrLogin(String loginuuid,String username,String password, Model model,HttpServletRequest request) {
        if (!StringUtils.isEmpty(loginuuid)) {
            request.getSession().getServletContext().setAttribute(loginuuid, true);
            request.getSession().getServletContext().setAttribute(loginuuid + "_username", username);
            request.getSession().getServletContext().setAttribute(loginuuid + "_passowrd", password);
        }
        return "登录成功！";
    }

    /*
     *
     * @author ygl
     * @description 前端二维码轮询登录状态
     * @date 2021/8/12/0012 21:11
     * @param request
     * @param loginuuid 标识唯一的id，与扫码同步用
     * @return java.lang.String
     */
    @RequestMapping("/login/check")
    @ResponseBody
    public String check(HttpServletRequest request, HttpServletResponse response, String loginuuid) {
        ServletContext servletContext = request.getSession().getServletContext();
        Object loginStatus = servletContext.getAttribute(loginuuid);
        String username = null;
        String password = null;
        if (loginStatus != null)
            if ((boolean) loginStatus) {
                try {
                    servletContext.setAttribute(loginuuid,false);
                    username= (String) servletContext.getAttribute(loginuuid+"_username");
                    password= (String) servletContext.getAttribute(loginuuid+"_passowrd");
                    //response.sendRedirect("/formLogin?username="+servletContext.getAttribute(loginuuid+"_username")+"&password="+servletContext.getAttribute(loginuuid+"_passowrd"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return username+"&"+password;
            }
        return null;
    }

    @RequestMapping("/login/toIndex")
    public String toIndex(Long userId, Model model, Principal principal) {
        //获取用户信息方法1
        //String name = principal.getName();
        //获取登录认证信息方法2
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if(authentication.getPrincipal() instanceof User){
            userId=((User) authentication.getPrincipal()).getId();
        }
        List<Menu> menus = menuService.findMenuByUserId(userId);
        model.addAttribute("menus", menus);
        return "index";
    }

    /*
     *
     * @author ygl
     * @description 测试登录成功后的接口
     * @date 2021/8/21/0021 16:16
     * @param request
     * @param token
     * @return java.lang.String
     */
    @RequestMapping("/getUserName")
    @ResponseBody
    public String getUserName(HttpServletRequest request, String token) {
        return "getUserName";
    }
}
